<template>
  <view :class="['vh100 bgParti', { dark: theme == 'dark' }]">
    <view class="flex between alcenter pt10 plr15 bor5 pb10 fixed w100">
      <view
        class="bd_input ptb10 plr10 radius4"
        @click="showP = true"
      >
        <view class="flex between">
          <text>{{ symbol.symbol }}</text></view
        >
      </view>

      <u-picker
        mode="selector"
        :default-selector="[0]"
        :confirm-text="confirmText"
        :cancel-text="cancelText"
        v-model="showP"
        :range="coinArr"
        @confirm="getSymbol"
        range-key="symbol"
      >
      </u-picker>
      <!-- <picker class="bd_input ptb10 plr10   radius4" :value="symbol" :range="coinArr" @change="getSymbol" range-key="symbol">
				
			</picker> -->
      <view
        class="bd_input ptb10 plr10 radius4"
        @click="showP2 = true"
      >
        <view class="flex between">
          <text>{{ buyMethod.name }}</text></view
        >
      </view>
      <u-picker
        mode="selector"
        :default-selector="[0]"
        :confirm-text="confirmText"
        :cancel-text="cancelText"
        v-model="showP2"
        :range="buyMethodArr"
        @confirm="getBuyMethod"
        range-key="name"
      >
      </u-picker>
      <view
        class="bd_input ptb10 plr10 radius4"
        @click="showP3 = true"
      >
        <view class="flex between">
          <text>{{ status.name }}</text></view
        >
      </view>
      <u-picker
        mode="selector"
        :default-selector="[0]"
        :confirm-text="confirmText"
        :cancel-text="cancelText"
        v-model="showP3"
        :range="statusArr"
        @confirm="getStatus"
        range-key="name"
      >
      </u-picker>
      <!-- <picker class="bd_input ptb10 plr10   radius4" :value="buyMethod" :range="buyMethodArr" @change="getBuyMethod" range-key="name">
				
			</picker> -->
      <!-- <picker class="bd_input ptb10 plr10   radius4" :value="status" :range="statusArr" @change="getStatus" range-key="name">
				<view class="flex between">
				
				<text>{{status.name}}</text></view>
			</picker> -->
      <view
        class="bgBlue ptb10 plr15 white radius4"
        @tap="search()"
        >{{ $t('bico.W480') }}</view
      >
    </view>
    <view class="list pt60 ft13">
      <!-- #ifdef APP-PLUS -->
      <view class="h20"> </view>
      <!-- #endif -->
      <view
        v-for="(item, index) in orderList"
        :key="index"
        class="plr15 bor5 mt10 pb10"
      >
        <view class="flex between mb10">
          <!-- 币种手数 -->
          <view class="">
            <text :class="item.compactType == 'BUY' ? 'green ft14' : 'red ft14'">{{
              item.compactType == 'BUY' ? $t('trade.buy') : $t('trade.sell')
            }}</text>
            <text class="ml5">{{ item.symbols }}</text>
            <!-- 杠杆  {{$t('trade.hand')}}-->
            <text class="ml5">{{ item.leverName }}</text>
          </view>
          <!-- 价格浮动 -->
          <view :class="item.lossProfit < 0 ? 'red' : 'green'">
            {{ item.lossProfit || '0.00' | toFixed2 }}({{ item.lossProfitRatio }})
          </view>
          <view>
            {{ typeMap(item.exitType) }}
            <u-icon
              @click="change(item)"
              class="uicon-arrow-down u-iconfont"
              style="margin-left: 20upx"
            />
          </view>
        </view>

        <view
          v-if="item.flag"
          class="flex between"
        >
          <view class="flex1">
            <!-- 持仓手数 -->
            <view class="">
              <view class="">
                {{ $t('bico.W481') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.numbers || '0.00' | toFixed2 }}
              </view>
            </view>
            <view class="mt10">
              <!-- 委托价格，平仓价 -->
              <view class="">
                {{ current == 0 ? $t('trade.delegate_price') : $t('trade.price_cang') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ current == 0 ? item.tradePrice : item.tradePrice || '0.0000' | toFixed2 }}
              </view>
            </view>
            <view class="mt10">
              <!--  -->
              <view class="">
                {{ $t('trade.price_zhiying') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.stopProfit || '0.00' | toFixed2 }}
              </view>
            </view>
            <!-- <view class="mt10">
								<view class="">
									{{$t('trade.num_zhehe')}}
								</view>
								<view class="mt5 gray_e ft14">
									{{item.number || '0.0000' |toFixed2}}
								</view>
							</view> -->
          </view>
          <view class="mr10 flex1">
            <view class="">
              <!--  -->
              <view class="">
                {{ $t('bico.W482') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.closeNumber || '0.00' | toFixed2 }}
              </view>
            </view>
            <view class="mt10">
              <!-- 当前价 -->
              <view class="">
                {{ $t('bico.W483') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.exitPrice || '0.0000' | toFixed2 }}
              </view>
            </view>
            <view class="mt10">
              <!-- 止损价 -->
              <view class="">
                {{ $t('trade.price_lose') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.stopLoss || '0.00' | toFixed2 }}
              </view>
            </view>
            <!-- <view class="mt10">
								 可用保证金
								<view class="">
									{{$t('trade.can_money')}}
								</view>
								<view class="mt5 gray_e ft14">
									{{item.positionPrice || '0.0000' |toFixed2}}
								</view>
							</view> -->
          </view>
          <view class="mr10 flex1">
            <!-- 保证金 -->
            <view class="">
              <view class="">
                {{ $t('bico.W484') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.positionPrice || '0.0000' | toFixed2 }}
              </view>
            </view>
            <!-- 手续费 -->
            <view class="mt10">
              <view class="">
                {{ $t('bico.W485') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.closeFeePrice || '0.00' | toFixed2 }}
              </view>
            </view>
          </view>
          <view class="flex1 tr">
            <!-- 平仓保证金 -->
            <view class="">
              <view class="">
                {{ $t('bico.W486') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.exitPositionPrice || '0.00' | toFixed2 }}
              </view>
            </view>

            <view class="mt10">
              <view class="">
                {{ $t('bico.W487') }}
              </view>
              <view class="mt5 gray_e ft14">
                {{ item.openHandPrice || '0.00' | toFixed2 }}
              </view>
            </view>
          </view>
        </view>
        <view
          v-if="item.flag"
          class="flex between"
        >
          <!-- 建仓时间 -->
          <view class="">
            <view class="mt10">
              {{ $t('bico.W488') }}
            </view>
            <view class="mt5 gray_e ft14">
              {{ item.createTime }}
            </view>
          </view>
        </view>
        <view
          v-if="item.flag"
          class="flex between mb10"
        >
          <!-- 平仓时间 -->
          <view class="">
            <view class="mt10">
              {{ $t('bico.W489') }}
            </view>
            <view class="mt5 gray_e ft14">
              {{ item.exitTime }}
            </view>
          </view>
        </view>
        <view
          v-if="item.flag"
          class="flex between mb9"
        >
          <view class="mt9">
            <view class="">
              {{ $t('bico.W490') }}
            </view>
            <view class="mt5 gray_e ft14">
              {{ item.orderNo }}
            </view>
          </view>
        </view>
        <!-- 按钮 -->
        <!-- <view class="flex tr mt15 jsend">
						<view class="bgBlue ptb10 plr15 white radius4" @tap="loss(item,index)">{{$t('lever.setys')}}</view>
						<view class="bgBlue ptb10 plr15 white radius4 ml10" @tap="closes(item.id,index)">{{$t('trade.pingcang')}}</view>
					</view> -->
      </view>
    </view>
    <view
      class="tc ptb30"
      v-if="orderList.length == 0"
    >
      <image
        src="/static/image/nodata.png"
        class="h50 wt50"
      ></image>
      <view class="gray7">{{ $t('home.norecord') }}</view>
    </view>
    <view
      class="tc gray7 ptb20"
      v-show="isBottom"
      >{{ $t('home.loading') }}...</view
    >
    <view
      class="tc gray7 ptb20"
      v-show="!hasMore && orderList.length > 10"
      >{{ $t('home.nomore') }}</view
    >
    <!-- 平仓弹窗 -->
    <uni-popup
      :show="closeTrades.closeTradeShow"
      @hidePopup="hideBtn"
      @comfirmPopup="comfirmClose"
      :msg="closeTrades.title"
    >
      <view class="uni-common-mt flex1 ft16">{{ $t('trade.confrim_ping') }}</view>
    </uni-popup>
    <!-- 设置止盈止损 -->
    <uni-popup
      :show="lossData.shows"
      @hidePopup="hideBtn"
      @comfirmPopup="lossClose"
      :msg="lossData.title"
    >
      <view class="uni-common-mt flex1 ft16">
        <view class="flex alcenter">
          <view class="ft13"> {{ $t('lever.price_zhiying') }}： </view>
          <view class="gray3">
            <uni-number-box
              class="gray3"
              :value="lossData.profitPrice"
              :max="100000000000000"
              @change="profitChange"
            />
          </view>
        </view>
        <view class="ft13 mt20 tc">
          {{ $t('lever.profit') }}：{{ lossData.expectedProfit || '0.00' | toFixed2 }}
        </view>
        <view class="flex alcenter mt10">
          <view class="ft13"> {{ $t('lever.price_lose') }}： </view>
          <view class="gray3">
            <uni-number-box
              class="gray3"
              :value="lossData.lossPrice"
              :max="100000000000000"
              @change="lossChange"
            />
          </view>
        </view>
        <view class="ft13 mt20 tc">
          {{ $t('lever.lose') }}：{{ lossData.expectedLoss || '0.00' | toFixed2 }}
        </view>
      </view>
    </uni-popup>
    <!-- 一键平仓 -->
    <uni-popup
      :show="allClose.shows"
      @hidePopup="hideBtn"
      @comfirmPopup="totalCloses"
      :msg="allClose.title"
    >
      <view class="uni-common-mt flex1 ft16 flex">
        <view
          class="ptb5 plr10 radius6 ft13"
          :class="closeType == 0 ? 'bgBlue white' : 'bor2 blue2'"
          @tap="closeType = 0"
          >{{ $t('lever.all_ping') }}</view
        >
        <view
          class="ml10 ptb5 plr10 radius6 ft13"
          :class="closeType == 1 ? 'bgGreen white' : 'green bor3'"
          @tap="closeType = 1"
          >{{ $t('lever.duo_ping') }}</view
        >
        <view
          class="ml10 ptb5 plr10 radius6 ft13"
          :class="closeType == 2 ? 'bgRed white' : 'red bor4'"
          @tap="closeType = 2"
          >{{ $t('lever.kong_ping') }}</view
        >
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import uniIcon from '../../components/uni-icon.vue';
import uniPopup from '@/components/uni-popup.vue';
import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue';
import { huobiTicket, contractList } from '../../common/apiString.js';
import typeMap from '../../common/cashFlowType.js';
import { myMixins } from '@/common/myMixins.js';
export default {
  mixins: [myMixins],
  components: {
    uniIcon,
    uniPopup,
    uniNumberBox
  },
  data() {
    return {
      showP: false,
      showP2: false,
      showP3: false,
      confirmText: this.$t('login').c1,
      cancelText: this.$t('login').c2,
      symbol: '',
      buyMethod: {},
      status: {},
      coinArr: [{ symbol: this.$t('bico.W491') }],
      buyMethodArr: [
        { code: '', name: this.$t('bico.W491') },
        { code: 'BUY', name: this.$t('bico.W492') },
        { code: 'SELL', name: this.$t('bico.W493') }
      ],
      statusArr: [
        { code: '', name: this.$t('bico.W491') },
        { code: 'HANDLE', name: this.$t('bico.W494') },
        { code: 'FIXED', name: this.$t('bico.W495') },
        { code: 'PROFIT', name: this.$t('bico.W496') },
        { code: 'LOSS', name: this.$t('bico.W497') }
      ],
      current: 0,
      risk: '0.00',
      totalRisk: '0.00',
      legalId: '',
      currencyId: '',
      contractType: false,
      orderList: [],
      page: 1,
      // 平仓弹窗
      closeTrades: {
        closeTradeShow: false,
        title: '',
        orderId: '',
        indexs: ''
      },
      isBottom: false,
      hasMore: true,
      lossData: {
        shows: false,
        title: this.$t('lever.setys'),
        datas: {},
        expectedProfit: '0.00',
        expectedLoss: '0.00',
        lossPrice: '',
        profitPrice: '',
        indexs: ''
      },
      allClose: {
        shows: false,
        title: this.$t('trade.confrim_ping')
      },
      closeType: 0
    };
  },
  filters: {
    toFixed2: function (value) {
      value = Number(value);
      return value.toFixed(2);
    },
    toFixed4: function (value) {
      value = Number(value);
      return value.toFixed(4);
    }
  },
  onLoad(e) {
    uni.setNavigationBarTitle({
      title: this.$t('bico.W498')
    });
    this.$utils.setTheme(this.theme);
    var that = this;
    this.contractType = e.contractType;
    console.log(e);
    if (e.legalId) {
      that.legalId = e.legalId;
      that.currencyId = e.currencyId;
    }
    that.orderList = [];
    that.init();
    that.getCoinArr();
  },
  onShow() {
    var that = this;
  },
  onHide() {},
  computed: {
    ...mapState({
      theme: state => state.theme
    })
  },
  methods: {
    change(item) {
      if ('flag' in item) {
        item.flag = !item.flag;
      } else {
        item.flag = false;
      }
    },
    typeMap(val) {
      return typeMap(val);
    },
    search() {
      var that = this;
      that.page = 1;
      that.orderList = [];
      that.init();
    },
    getBuyMethod(evt) {
      var that = this;
      if (isNaN(evt[0])) {
        return;
      }
      that.buyMethod = that.buyMethodArr[evt[0]];
    },
    getSymbol(evt) {
      var that = this;
      if (isNaN(evt[0])) {
        return;
      }
      that.symbol = that.coinArr[evt[0]];
    },
    getStatus(evt) {
      var that = this;
      if (isNaN(evt[0])) {
        return;
      }
      that.status = that.statusArr[evt[0]];
    },
    getCoinArr() {
      let that = this;
      this.$utils.initData({ url: huobiTicket, data: { type: 1 }, type: 'post' }, (res, msg) => {
        uni.stopPullDownRefresh();
        that.coinArr = res;
        that.symbol = that.coinArr[0];
        that.status = that.statusArr[0];
        that.buyMethod = that.buyMethodArr[0];
        //that.coinArr = res;
      });
    },
    init() {
      var that = this;
      var symbol = that.symbol.symbol == this.$t('bico.W491') ? '' : that.symbol.symbol;
      var status = that.status.name == this.$t('bico.W491') ? '' : that.status.code;
      var buyMethod = that.buyMethod.name == this.$t('bico.W491') ? '' : that.buyMethod.code;

      that.$utils.initDataToken(
        {
          url: contractList,
          type: 'get',
          data: {
            type: 'Y',
            showMethod: 'ALL',
            symbols: symbol,
            status: status,
            buyMethod: buyMethod,
            current: that.page,
            size: 100,
            contractType: that.contractType
          }
        },
        res => {
          console.log(2223,res);
          if (res.records.length > 0) {
			  that.orderList = []
            res.records.forEach((item, i) => {
              item.flag = true;
              that.orderList.push(item);
            });
            if (that.page == 1) {
              that.orderTrade();
            }
          }
        }
      );
    },
    // 平仓
    closes(ids, indexs) {
      var that = this;
      that.closeTrades.orderId = ids;
      that.closeTrades.indexs = indexs;
      that.closeTrades.closeTradeShow = true;
    },
    hideBtn() {
      var that = this;
      that.closeTrades.closeTradeShow = false;
      that.lossData.shows = false;
      that.allClose.shows = false;
    },
    comfirmClose() {
      var that = this;
      that.closeTrades.closeTradeShow = false;
      that.$utils.initDataToken(
        {
          url: 'lever/close',
          type: 'POST',
          data: {
            id: that.closeTrades.orderId
          }
        },
        res => {
          that.$utils.showLayer(res);
          that.$socket.closeSocket();
          that.orderTrade();
          setTimeout(function () {
            that.closeTrades.orderId = '';
            that.orderList.splice(that.closeTrades.indexs, 1);
          }, 2000);
        }
      );
    },
    // 设置止盈止损
    loss(options, indexs) {
      var that = this;
      that.lossData.datas = options;
      that.lossData.shows = true;
      that.lossData.indexs = indexs;
      if (options.target_profit_price > 0) {
        that.lossData.profitPrice = Number(options.target_profit_price);
        if (options.type == 1) {
          if (that.lossData.profitPrice > options.price) {
            that.lossData.expectedProfit =
              (that.lossData.profitPrice - options.price) * options.share;
          } else {
            that.lossData.expectedProfit = '0.00';
          }
        } else {
          if (options.price > that.lossData.profitPrice) {
            that.lossData.expectedProfit =
              (options.price - that.lossData.profitPrice) * options.share;
          } else {
            that.lossData.expectedProfit = '0.00';
          }
        }
      } else {
        that.lossData.profitPrice = Number(options.update_price);
      }
      if (options.stop_loss_price > 0) {
        that.lossData.lossPrice = Number(options.stop_loss_price);
        if (options.type == 1) {
          if (options.price > that.lossData.lossPrice) {
            that.lossData.expectedLoss = (options.price - that.lossData.lossPrice) * options.share;
          } else {
            that.lossData.expectedLoss = '0.00';
          }
        } else {
          if (that.lossData.lossPrice > options.price) {
            that.lossData.expectedLoss = (that.lossData.lossPrice - options.price) * options.share;
          }
        }
      } else {
        that.lossData.lossPrice = Number(options.update_price);
      }
      console.log(options, that.lossData);
    },
    profitChange(value) {
      var that = this;
      that.lossData.profitPrice = value;
      if (that.lossData.datas.type == 1) {
        if (that.lossData.profitPrice > that.lossData.datas.price) {
          that.lossData.expectedProfit =
            (that.lossData.profitPrice - that.lossData.datas.price) * that.lossData.datas.share;
        } else {
          that.lossData.expectedProfit = '0.00';
        }
      } else {
        if (that.lossData.datas.price > that.lossData.profitPrice) {
          that.lossData.expectedProfit =
            (that.lossData.datas.price - that.lossData.profitPrice) * that.lossData.datas.share;
        } else {
          that.lossData.expectedProfit = '0.00';
        }
      }
    },
    lossChange(value) {
      var that = this;
      that.lossData.lossPrice = value;
      if (that.lossData.datas.type == 1) {
        if (that.lossData.datas.price > that.lossData.lossPrice) {
          that.lossData.expectedLoss =
            (that.lossData.datas.price - that.lossData.lossPrice) * that.lossData.datas.share;
        } else {
          that.lossData.expectedLoss = '0.00';
        }
      } else {
        if (that.lossData.lossPrice > that.lossData.datas.price) {
          that.lossData.expectedLoss =
            (that.lossData.lossPrice - that.lossData.datas.price) * that.lossData.datas.share;
        } else {
          that.lossData.expectedLoss = '0.00';
        }
      }
    },
    lossClose() {
      var that = this;
      // if(that.lossData.datas.type == 1){
      // 	if(that.lossData.expectedProfit == 0){
      // 		that.$utils.showLayer('设置的止盈价需要高于开仓价');
      // 		return false;
      // 	}
      // 	if(that.lossData.expectedLoss == 0){
      // 		that.$utils.showLayer('设置的止损价不能高于开仓价');
      // 		return false;
      // 	}
      // }else{
      //
      // }
      that.$utils.initDataToken(
        {
          url: 'lever/setstop',
          type: 'POST',
          data: {
            id: that.lossData.datas.id,
            target_profit_price: that.lossData.profitPrice,
            stop_loss_price: that.lossData.lossPrice
          }
        },
        res => {
          that.lossData.shows = false;
          that.$utils.showLayer(res);
          that.orderList[that.lossData.indexs].target_profit_price = that.lossData.profitPrice;
          that.orderList[that.lossData.indexs].stop_loss_price = that.lossData.lossPrice;
        }
      );
    },

    //一键平仓
    totalCloses() {
      var that = this;
      that.$utils.initDataToken(
        {
          url: 'lever/batch_close',
          type: 'POST',
          data: {
            type: that.closeType
          }
        },
        res => {
          that.allClose.shows = false;
          that.$utils.showLayer(res);
          that.page = 1;
          that.orderList = [];
          that.that.init();
        }
      );
    },
    onPullDownRefresh() {
      this.page = 1;
      this.init();
    },
    onReachBottom() {
      if (!this.hasMore) return;
      this.page++;
      this.init();
    },
    // 订单socket
    orderTrade() {
      var that = this;
      var tokens = uni.getStorageSync('token');
      that.$socket.listenFun(
        [
          { event: 'login', params: tokens },
          { event: 'sub', params: 'lever_trade' },
          { event: 'sub', params: 'lever_closed' }
        ],
        res => {
          // that.$socket.listenFun([{event: "login", params: tokens}],(res)=>{
          let msg = JSON.parse(res);
          var datas = that.orderList;
          if (msg.type == 'lever_trade') {
            var data1 = msg.trades_all;
            if (that.legalId == msg.legal_id) {
              that.risk = msg.hazard_rate;
              that.totalRisk = msg.profits_all;
            }
            data1.forEach((item, index) => {
              datas.forEach((itm, inx) => {
                if (itm.currency == item.currency && itm.legal == item.legal && item.id == itm.id) {
                  that.orderList.splice(inx, 1, item);
                }
              });
            });
          }
          if (msg.type == 'lever_closed') {
            var data2 = msg.id;
            data2.forEach((item, index) => {
              datas.forEach((itm, inx) => {
                if (item == itm.id) {
                  that.orderList.splice(inx, 1);
                }
              });
            });
          }
        }
      );
    }
  }
};
</script>

<style>
page {
  background: #f7f7fb;
}
/*.uni-input-input{
		color: #333;
	} */
.wt50 {
  width: 34px;
  height: 38px;
}
</style>
